package com.quanyan.ic.protocol.server.handler;

import com.quanyan.ic.protocol.MessageType;
import com.quanyan.ic.protocol.codec.protobuf.ICMessageBuilder;
import com.quanyan.ic.protocol.codec.protobuf.ICMessageProto;
import com.quanyan.ic.protocol.server.LightServer;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by zhuo.shi on 2017/5/31.
 */
public class HeartBeatRespHandler extends ChannelInboundHandlerAdapter {

    private static Logger logger = LoggerFactory.getLogger(HeartBeatRespHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ICMessageProto.ICMessage message = (ICMessageProto.ICMessage) msg;
        //客户端以固定频率发送心跳给服务端，服务端回应心跳消息
        if (message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_REQ.value()) {

//            if (logger.isDebugEnabled()){
//                logger.info("Receive client heart beat req message: {}", message);
//            }

            //当服务端挂掉后，重启，如果客户端心跳发过来，客户端自动复活
            String pid = String.valueOf(message.getHeader().getPid());
            if (!LightServer.getSessionChannelMap().containsKey(pid)) {
                logger.info("add session: {}, this client reconnected", ctx.channel());
                LightServer.getSessionChannelMap().put(pid, ctx.channel());
            }

            //应答客户端心跳，Server复活了
            ctx.writeAndFlush(ICMessageBuilder.buildHeatBeatMsg(message.getHeader().getPid(), MessageType.HEARTBEAT_RESP));

        } else {
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (cause.getMessage().startsWith("Connection reset")
                && (ctx.channel().remoteAddress().toString().startsWith("/10.") || ctx.channel().remoteAddress().toString().startsWith("/100."))) {
            logger.info("health check!");
            return;
        }
//        super.exceptionCaught(ctx, cause);
        ctx.fireExceptionCaught(cause);
    }

}
